package com.qiyou.util;

import java.lang.reflect.Field;

/**
 * 数据转换工具类，主要用于转换一些数据
 * 
 * @author 杨强
 * 
 */
public class TransformUtil {

    /**
     * 将bean对象的属性值转换成数组
     * 
     * @param bean
     *            bean对象
     * @param isIgnoreFirst
     *            是否忽略首个属性，主要针对主键自动增长的bean对象，如果为true，不会将首个属性加入到数组
     * @return bean对象的属性值数组，数组中的值与实体bean属性顺序一致
     */
    public static Object[] beanTOArray(Object bean, boolean isIgnoreFirst) {
        Object[] array = null;
        if (null == bean) {
            return array;
        }
        Field[] fields = bean.getClass().getDeclaredFields();
        if (isIgnoreFirst) {
            array = new Object[fields.length - 1];
            for (int i = 1; i < fields.length; i++) {
                fields[i].setAccessible(true);
                try {
                    array[i - 1] = fields[i].get(bean);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                fields[i].setAccessible(false);
            }
        } else {
            array = new Object[fields.length];
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                try {
                    array[i] = fields[i].get(bean);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                fields[i].setAccessible(false);
            }
        }
        return array;
    }

    /**
     * 将数组值转换为一个bean对象<br>
     * <b>注意：</b>数组中的值必须与对应的bean实体属性顺序一致
     * 
     * @param array
     *            属性值数组
     * @param cls
     *            bean对象类型
     * @return bean对象
     */
    public static Object arrayToBean(Object[] array, Class<?> cls) {
        Object bean = null;
        if (null == array || null == cls) {
            return bean;
        }
        Field[] fields = cls.getDeclaredFields();
        try {
            bean = cls.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < array.length; i++) {
            fields[i].setAccessible(true);
            try {
                fields[i].set(bean, array[i]);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            fields[i].setAccessible(false);
        }
        return bean;
    }
}
